#!/usr/bin/python
# -*- coding: UTF-8 -*-

#reference https://segmentfault.com/q/1010000007410506/a-1020000007418663

import pyexiv2 as ev
import os
import time
import datetime

import socket
import struct
def to_deg(value, loc):
    """convert decimal coordinates into degrees, munutes and seconds tuple
       
    Keyword arguments: value is float gps-value, loc is direction list ["S", "N"] or ["W", "E"]
    return: tuple like (25, 13, 48.343 ,'N')
    """
    if value < 0:
        loc_value = loc[0]
    elif value > 0:
        loc_value = loc[1]
    else:
        loc_value = ""
    abs_value = abs(value)
    deg =  int(abs_value)
    t1 = (abs_value-deg)*60
    min = int(t1)
    sec = round((t1 - min)* 60, 5)
    return (deg, min, sec, loc_value)    


def set_gps_location(file_name, lat, lng , height):
    """Adds GPS position as EXIF metadata

    Keyword arguments:
    file_name -- image file 
    lat -- latitude (as float)
    lng -- longitude (as float)

    """
    lat_deg = to_deg(lat, ["S", "N"])
    lng_deg = to_deg(lng, ["W", "E"])


    print lat_deg
    print lng_deg
    print height

    # class pyexiv2.utils.Rational(numerator, denominator) => convert decimal coordinates into degrees, munutes and seconds
    exiv_lat = (ev.Rational(lat_deg[0]*60+lat_deg[1],60),ev.Rational(lat_deg[2]*100,6000), ev.Rational(0, 1))
    exiv_lng = (ev.Rational(lng_deg[0]*60+lng_deg[1],60),ev.Rational(lng_deg[2]*100,6000), ev.Rational(0, 1))

    height_tag = '0'
    if height < 0:
        height_tag = '1'
        height = -height


    exiv_height = ev.Rational( height*100,100)
    
    exiv_image = ev.ImageMetadata(file_name)
    exiv_image.read()

    #print exiv_image["Exif.GPSInfo.GPSLatitude"]
    #print exiv_image["Exif.GPSInfo.GPSLatitudeRef"]

    #print exiv_image["Exif.GPSInfo.GPSAltitude"]
    #print exiv_image["Exif.GPSInfo.GPSAltitudeRef"]
    
    # modify GPSInfo of image
    exiv_image["Exif.GPSInfo.GPSLatitude"] = exiv_lat
    exiv_image["Exif.GPSInfo.GPSLatitudeRef"] = lat_deg[3]
    exiv_image["Exif.GPSInfo.GPSLongitude"] = exiv_lng
    exiv_image["Exif.GPSInfo.GPSLongitudeRef"] = lng_deg[3]
    exiv_image["Exif.GPSInfo.GPSAltitude"] = exiv_height
    exiv_image["Exif.GPSInfo.GPSAltitudeRef"] = height_tag
    exiv_image["Exif.Image.GPSTag"] = 654
    exiv_image["Exif.GPSInfo.GPSMapDatum"] = "WGS-84"
    exiv_image["Exif.GPSInfo.GPSVersionID"] = '2 2 0 0'

    exiv_image.write()

def take_a_photo():
    #take a photo
    #command:raspistill -o image.jpg 

    dtime = datetime.datetime.now()
    ans_time = time.mktime(dtime.timetuple())

    filename = "/home/liuxibo/GPSCamera/DICM/%s.jpg" % ans_time

    output = os.popen('raspistill -t 1 -o %s' % filename)
    print output.read()
    print "take a photo %s" % filename
    return filename



#creat a udp server
address=('0.0.0.0',9999)
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(address)
print 'udp server listern on port:9999'
while 1:
    data,addr=s.recvfrom(2048)
    if not data:
        break
    #print "got data from",addr
    #print data
    #python for unpack struct
    #http://blog.csdn.net/iloveyin/article/details/40743399
    lat, lng, alt = struct.unpack("@fff", data)
    print "take a photo :%f,%f,%f" % (lat, lng, alt) 
    filename = take_a_photo()
    set_gps_location(filename, lat, lng ,alt)
 

s.close()



print 'end'